<?php
declare (strict_types=1);

namespace app\admin\logic\finance;

use app\admin\logic\system\Log;
use app\admin\model\finance\Refund as RefundModel;
use app\common\exception\LogicException;
use app\common\logic\payment\admin\PaymentOrderItem;
use app\common\model\payment\admin\PaymentTransaction;
use app\common\model\payment\PaymentOrder;
use app\course\model\base\CourseStudent;
use think\facade\Db;

/**
 * Class Refund
 *
 * @package app\admin\logic\finance
 */
class Refund extends RefundModel
{
    /**
     * 退款列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2022/1/21
     *
     * @param array $map
     * @return \think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $map = [])
    {
        return $this->where($map)->order('create_time')->paginate($this->getListRows())->each(function ($item) {
            // 查询订单名称：根据订单号查询子订单的数据名称
            $item->order_title = $this->getOrderTitle($item->order_no);
            // 查询订单支付用户、支付时间、支付金额、支付方式
            $this->paddingPaymentInfo($item);
        });
    }

    /**
     * 获取订单名称
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2022/1/21
     *
     * @param $orderNo
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getOrderTitle($orderNo)
    {
        /** @var PaymentOrderItem $paymentOrderItemLogic */
        $paymentOrderItemLogic = app(PaymentOrderItem::class);
        $order                 = $paymentOrderItemLogic->getInfoByOrderNo($orderNo);
        if (!$order->isEmpty()) {
            $current = $order[0];
            return $current->title;
        }

        return '【资源已被删除】';
    }

    /**
     * 填充订单信息
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2022/1/21
     *
     * @param $item
     */
    private function paddingPaymentInfo($item)
    {
        /** @var PaymentTransaction $payment */
        $payment = app(PaymentTransaction::class);
        $info    = $payment->with(['user'])->where('order_no', $item->order_no)->findOrEmpty();
        if (!$info->isEmpty()) {
            $item->payment_type = $info->payment_type_text;
            $item->payment      = $info->payment;
            $item->payment_time = $info->payment_time;
            // 支付用户
            if ($user = $info->getAttr('user')) {
                $item->user = $user->phone;
            }
        }
    }

    /**
     * 管理员操作退款
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/10
     *
     * @param string $orderSubNo 子订单号
     */
    public function orderRefundByAdmin(string $orderSubNo)
    {
        /**
         * 检查是否是单商品订单，1是 2不是
         * 1：删除主订单及子订单
         * 2：修改主订单支付金额 删除子订单
         * 修改学员表有效期
         */
        Db::startTrans();
        try {
            $subOrderData  = app(PaymentOrderItem::class)->where('order_sub_no', $orderSubNo)->findOrFail();
            $orderNo       = $subOrderData->order_no;
            $singleProduct = app(PaymentOrderItem::class)->where('order_no', $orderNo)->count();
            $orderData     = app(PaymentOrder::class)->where('order_no', $orderNo)->findOrFail();
            if (in_array($subOrderData->product_type_id, [1, 2, 3, 4])) {
                $studentData = app(CourseStudent::class)->whereUserId($subOrderData->user_id)->whereCourseId($subOrderData->product_id)->findOrEmpty();
                if (!$studentData->isEmpty()) {
                    $studentData->expire_time = time();
                    if (!$studentData->save()) throw new LogicException('处理失败');
                }
            }
            if (1 == $singleProduct) {
                if (!$subOrderData->delete() || !$orderData->delete()) throw new LogicException('处理失败');
            } else {
                $orderData->payment -= $subOrderData->payment;
                if (!$orderData->save() || !$subOrderData->delete()) throw new LogicException('处理失败.');
            }
            Log::write('操作退款【' . $orderSubNo . '】', 'order', 'refund', true);
            Db::commit();
        } catch (LogicException $exception) {
            Db::rollback();
            throw new LogicException($exception->getMessage());
        } catch (\Exception $exception) {
            Db::rollback();
            throw new LogicException($exception->getMessage());
        }
    }

}